package top.tomxwd.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.tomxwd.common.Result;
import top.tomxwd.entity.Payment;
import top.tomxwd.service.PaymentService;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author xieweidu
 * @createDate 2020-07-07 23:40
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String port;

    @PostMapping("/create")
    public Result<Integer> create(@RequestBody Payment payment) {
        Integer i = paymentService.create(payment);
        log.info("payment{}插入结果：{}", port, i);
        if (i > 0) {
            return new Result<>(200, "保存成功", i);
        } else {
            return new Result<>(500, "保存失败");
        }
    }

    @GetMapping("/getById/{id}")
    public Result<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("payment[{}]根据id：{}查询Payment为：{}", port, id, payment);
        if (payment != null) {
            return new Result<>(200, "查询成功", payment);
        } else {
            return new Result<>(400, "找不到");
        }
    }

    @GetMapping("/timeout")
    public String timeout(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String header = request.getHeader("X-Request-red");
            System.out.println("header = " + header);
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }

}
